﻿//======================================================
//==     (c)2008 aspxcms inc by NeTCMS v1.0              ==
//==          Forum:bbs.aspxcms.com                   ==
//==         Website:www.aspxcms.com                  ==
//======================================================
using System;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Collections;
using NetCMS.DALFactory;
using NetCMS.Model;
using NetCMS.Global;
using NetCMS.DALProfile;
using NetCMS.Config;
using NetCMS.Control;
using System.Collections.Generic;
using Discuz.Entity;
using Discuz.Common;

namespace NetCMS.DALSQLServer
{
    public class Collect : DbBase, ICollect
    {
        public DataTable GetFolderSitePage(int FolderID, int PageIndex, int PageSize, out int RecordCount, out int PageCount)
        {

            if (FolderID < 1)
            {

                SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
                cn.Open();
                int nf = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "'", null));
                int ns = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and (Folder is null or Folder=0)", null));
                RecordCount = nf + ns;
                if (RecordCount % PageSize == 0)
                    PageCount = RecordCount / PageSize;
                else
                    PageCount = RecordCount / PageSize + 1;
                if (PageIndex > PageCount)
                    PageIndex = PageCount;
                if (PageIndex < 1)
                    PageIndex = 1;
                int nStart = PageSize * (PageIndex - 1);
                string Sql = "(select 0 as TP,ID,SiteFolder as SName,'' as objURL,'' as LockState,0 as cjcount,0 as allcount,0 as needcount,'' as topchapter,'' as cjstate from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "') union (select 1 as TP,ID,SiteName as SName,objURL,case when LinkSetting is null or PagebodySetting is null or  PageTitleSetting is null then '不可用' else '有效' end as LockState, cjcount, allcount, needcount,topchapter,cjstate  from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and (Folder is null or Folder=0))";
                SqlDataAdapter ap = new SqlDataAdapter(Sql, cn);
                DataSet st = new DataSet();
                ap.Fill(st, nStart, PageSize, "REST");
                DataTable tb = st.Tables[0];
                st.Dispose();
                if (cn.State == ConnectionState.Open)
                    cn.Close();
                return tb;
            }
            else
            {
                return DbHelper.ExecutePage(DBConfig.CollectConString, "1 as TP,ID,SiteName as SName,objURL,case when LinkSetting is null or PagebodySetting is null or  PageTitleSetting is null then '不可用' else '有效' end as LockState, cjcount, allcount, needcount,topchapter,cjstate ", Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and Folder=" + FolderID, "ID", "Order by sitename,ID", PageIndex, PageSize, out RecordCount, out PageCount, null);
            }
        }


        public int GetAutoCollectRules()
        {
            string sql = "insert into cjqueue(ruleid,collecttime)";
            sql += "select ID,getdate() from NT_Collect_Site where ChannelID='1' and id not in(select ruleid from cjqueue) and cjstate=1 Order by sitename,ID";
            return DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sql, null);
            
        }

        /// <summary>
        /// 根据cjqueue获取一条规则
        /// </summary>
        /// <returns></returns>
        public DataTable GetOneRule(string top)
        {
            string Sql = "select "+top+" c.* from cjqueue q join nt_collect_site c on c.id=q.ruleid where c.cjstate=1 order by q.collecttime";
            return DbHelper.ExecuteTable(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }

        public void SiteCopy(int id)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            try
            {
                string Sql = "select * from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and ID=" + id;
                IDataReader rd = DbHelper.ExecuteReader(cn, CommandType.Text, Sql, null);
                string snm = "", Column = "";
                if (rd.Read())
                {
                    snm = rd["SiteName"].ToString();
                    for (int i = 0; i < rd.FieldCount; i++)
                    {
                        string clnm = rd.GetName(i);
                        if (!(clnm.Equals("ID") || clnm.Equals("SiteName")))
                        {
                            Column += "," + clnm;
                        }
                    }
                }
                else
                {
                    rd.Close();
                    throw new Exception("0%没有找到该记录");
                }
                rd.Close();
                string snewnm = "复件 " + snm;
                int n = 2;
                while (Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from " + Pre + "Collect_Site where SiteName='" + snewnm + "'", null)) > 0)
                {
                    snewnm = "复件(" + n + ") " + snm;
                    n++;
                }
                Sql = "insert into " + Pre + "Collect_Site (SiteName" + Column + ") select '" + snewnm + "' as NewName" + Column + " from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and ID=" + id;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void FolderCopy(int id)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            try
            {
                string Sql = "select SiteFolder from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "' and ID=" + id;
                object snm = DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null);
                if (snm == null)
                    throw new Exception("没有找到相关目录的记录");
                int n = 2;
                string snewnm = "复件 " + snm;
                /*
                if (Regex.Match(snm,@"^复件\s").Success)
                {
                    snewnm = "复件(" + n + ")" + snm;
                    n++;
                }
                else if (Regex.Match(snm, @"^复件(/d)").Success)
                {
                    n = int.Parse(Regex.Match(snm, @"(?<=复件\()\d+?(?=\).+)").Value);
                    n++;
                    snewnm = "复件(" + n + ")" + snm;
                    n++;
                }
                else
                {
                    snewnm = "复件 " + snm;
                }
                 */
                while (Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, "select count(*) from " + Pre + "Collect_SiteFolder where SiteFolder='" + snewnm + "'", null)) > 0)
                {
                    snewnm = "复件(" + n + ") " + snm;
                    n++;
                }
                Sql = "insert into " + Pre + "Collect_SiteFolder (SiteFolder,SiteFolderDetail,ChannelID) select '" + snewnm + "' as NewName,SiteFolderDetail,ChannelID from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "' and ID=" + id;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void FolderDelete(int id)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            try
            {
                string Sql = "select count(*) from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and Folder=" + id;
                int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, null));
                if (n > 0)
                    throw new Exception("该栏目下有站点,不能删除!");
                Sql = "Delete from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "' and ID=" + id;
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public void SiteDelete(int id)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            SqlTransaction tran = cn.BeginTransaction();
            try
            {
                string[] Sql = new string[2];
                DbHelper.ExecuteNonQuery(tran, CommandType.Text, "Delete from " + Pre + "Collect_RuleApply where SiteID=" + id, null);
                DbHelper.ExecuteNonQuery(tran, CommandType.Text, "Delete from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and ID=" + id, null);
                tran.Commit();
            }
            catch
            {
                tran.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public DataTable GetFolder(int id, bool all)
        {
            string Sql = "select ID,SiteFolder,SiteFolderDetail from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "'";
            if (!all)
                Sql += " and ID=" + id;
            return DbHelper.ExecuteTable(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }
        public DataTable GetSite(int id)
        {
            string Sql = "";            
            Sql = "select a.*,b.OldContent,b.ReContent,b.IgnoreCase from " + Pre + "Collect_Site a left join (" + Pre + "Collect_Rule b inner join " + Pre + 
                "Collect_RuleApply c on b.ID=c.RuleID) on c.SiteID=a.ID where a.ChannelID='1' and a.ID=" + id;           
           
            return DbHelper.ExecuteTable(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }
        public int SiteAdd(CollectSiteInfo st)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            try
            {
                string Sql = "select count(*) from " + Pre + "Collect_Site where ChannelID='" + Current.SiteID + "' and SiteName=@SiteName";
                SqlParameter parm = new SqlParameter("@SiteName", SqlDbType.NVarChar, 50);
                parm.Value = st.SiteName;
                int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, parm));
                if (n > 0)
                {
                    cn.Close();
                    throw new Exception("采集站点名称重复!");
                }
                Sql = "insert into " + Pre + "Collect_Site (";
                Sql += "SiteName,objURL,Folder,SaveRemotePic,Audit,IsReverse,IsAutoPicNews,TextTF";
                Sql += ",IsStyle,IsDIV,IsA,IsClass,IsFont,IsSpan,IsObject,IsIFrame,IsScript,Encode,ClassID,ChannelID";
                Sql += ",IsAutoCollect,cjcount";
                Sql += ") values (";
                Sql += "@SiteName,@objURL,@Folder,@SaveRemotePic,@Audit,@IsReverse,@IsAutoPicNews,@TextTF";
                Sql += ",@IsStyle,@IsDIV,@IsA,@IsClass,@IsFont,@IsSpan,@IsObject,@IsIFrame,@IsScript,@Encode,@ClassID,'" + Current.SiteID + "',";
                Sql += "@IsAutoCollect,@cjcount)";
                Sql += ";SELECT @@IDENTITY";
                int result = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, GetParameters(st)));
                return result;
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public int FolderAdd(string Name, string Description)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            string Sql = "select count(*) from " + Pre + "Collect_SiteFolder where ChannelID='" + Current.SiteID + "' and SiteFolder=@SiteFolder";
            SqlParameter prm = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            prm.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, prm));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("栏目名称重复");
            }
            Sql = "insert into " + Pre + "Collect_SiteFolder (SiteFolder,SiteFolderDetail,ChannelID) values (@SiteFolder,@SiteFolderDetail,'" + Current.SiteID + "');SELECT @@IDENTITY";
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            param[0].Value = Name;
            param[1] = new SqlParameter("@SiteFolderDetail", SqlDbType.NText);
            param[1].Value = Description.Trim().Equals("") ? DBNull.Value : (object)Description;
            n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
            cn.Close();
            return n;
        }
        public void SiteUpdate(CollectSiteInfo st, int step)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            try
            {
                SqlParameter[] param = null;
                string Sql = "";
                if (step == 1)
                {
                    #region 第一步
                    Sql = "select count(*) from " + Pre + "Collect_Site where SiteName=@SiteName and ChannelID='" + Current.SiteID + "' and ID<>@ID";
                    SqlParameter[] parm = new SqlParameter[2];
                    parm[0] = new SqlParameter("@SiteName", SqlDbType.NVarChar, 50);
                    parm[0].Value = st.SiteName;
                    parm[1] = new SqlParameter("@ID", SqlDbType.Int);
                    parm[1].Value = st.ID;
                    int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, parm));
                    if (n > 0)
                    {
                        cn.Close();
                        throw new Exception("采集站点名称重复!");
                    }
                    Sql = "update " + Pre + "Collect_Site Set SiteName=@SiteName,objURL=@objURL,Folder=@Folder,ClassID=@ClassID,";
                    Sql += "SaveRemotePic=@SaveRemotePic,Audit=@Audit,IsReverse=@IsReverse,IsAutoPicNews=@IsAutoPicNews,TextTF=@TextTF,";
                    Sql += "IsStyle=@IsStyle,IsDIV=@IsDIV,IsA=@IsA,IsClass=@IsClass,IsFont=@IsFont,IsSpan=@IsSpan,";
                    Sql += "IsObject=@IsObject,IsIFrame=@IsIFrame,IsScript=@IsScript,Encode=@Encode,IsAutoCollect=@IsAutoCollect,cjcount=@cjcount";
                    Sql += " where ChannelID='" + Current.SiteID + "' and ID=" + st.ID;
                    param = GetParameters(st);
                    #endregion 第一步
                }
                else if (step == 2)
                {
                    #region 第二步
                    Sql = "update " + Pre + "Collect_Site set ListSetting=@ListSetting,OtherPageSetting=@OtherPageSetting,";
                    Sql += "StartPageNum=@StartPageNum,EndPageNum=@EndPageNum,OtherType=@OtherType where ChannelID='" + Current.SiteID + "' and ID=" + st.ID;
                    param = new SqlParameter[5];
                    param[0] = new SqlParameter("@ListSetting", SqlDbType.NVarChar, 4000);
                    param[0].Value = st.ListSetting;
                    param[1] = new SqlParameter("@OtherPageSetting", SqlDbType.NVarChar, 4000);
                    param[1].Value = st.OtherPageSetting.Trim().Equals("") ? DBNull.Value : (object)st.OtherPageSetting;
                    param[2] = new SqlParameter("@StartPageNum", SqlDbType.Int);
                    param[2].Value = st.StartPageNum < 0 ? DBNull.Value : (object)st.StartPageNum;
                    param[3] = new SqlParameter("@EndPageNum", SqlDbType.Int);
                    param[3].Value = st.EndPageNum < 0 ? DBNull.Value : (object)st.EndPageNum;
                    param[4] = new SqlParameter("@OtherType", SqlDbType.Int);
                    param[4].Value = st.OtherType;
                    #endregion 第二步
                }
                else if (step == 3)
                {
                    #region 第三步
                    Sql = "update " + Pre + "Collect_Site set LinkSetting=@LinkSetting where ChannelID='" + Current.SiteID + "' and ID=" + st.ID;
                    param = new SqlParameter[1];
                    param[0] = new SqlParameter("@LinkSetting", SqlDbType.NVarChar, 4000);
                    param[0].Value = st.LinkSetting;
                    #endregion 第三步
                }
                else if (step == 4)
                {
                    #region 第四步
                    Sql = "Update " + Pre + "Collect_Site set PageTitleSetting=@PageTitleSetting,PagebodySetting=@PagebodySetting";
                    Sql += ",AuthorSetting=@AuthorSetting,SourceSetting=@SourceSetting,AddDateSetting=@AddDateSetting,HandSetAuthor=@HandSetAuthor";
                    Sql += ",HandSetSource=@HandSetSource,HandSetAddDate=@HandSetAddDate,OtherNewsType=@OtherNewsType";
                    Sql += ",OtherNewsPageSetting=@OtherNewsPageSetting where ChannelID='" + Current.SiteID + "' and ID=" + st.ID;
                    param = new SqlParameter[10];
                    param[0] = new SqlParameter("@PageTitleSetting", SqlDbType.NVarChar, 4000);
                    param[0].Value = st.PageTitleSetting;
                    param[1] = new SqlParameter("@PagebodySetting", SqlDbType.NVarChar, 4000);
                    param[1].Value = st.PagebodySetting;
                    param[2] = new SqlParameter("@AuthorSetting", SqlDbType.NVarChar, 4000);
                    param[2].Value = st.AuthorSetting.Equals("") ? DBNull.Value : (object)st.AuthorSetting;
                    param[3] = new SqlParameter("@SourceSetting", SqlDbType.NText);
                    param[3].Value = st.SourceSetting.Equals("") ? DBNull.Value : (object)st.SourceSetting;
                    param[4] = new SqlParameter("@AddDateSetting", SqlDbType.NText);
                    param[4].Value = st.AddDateSetting.Equals("") ? DBNull.Value : (object)st.AddDateSetting;
                    param[5] = new SqlParameter("@HandSetAuthor", SqlDbType.NVarChar, 100);
                    param[5].Value = st.HandSetAuthor.Equals("") ? DBNull.Value : (object)st.HandSetAuthor;
                    param[6] = new SqlParameter("@HandSetSource", SqlDbType.NVarChar, 100);
                    param[6].Value = st.HandSetSource.Equals("") ? DBNull.Value : (object)st.HandSetSource;
                    param[7] = new SqlParameter("@HandSetAddDate", SqlDbType.DateTime);
                    param[7].Value = (st.HandSetAddDate.Year < 1753) ? DBNull.Value : (object)st.HandSetAddDate;
                    param[8] = new SqlParameter("@OtherNewsType", SqlDbType.Int);
                    param[8].Value = st.OtherNewsType;
                    param[9] = new SqlParameter("@OtherNewsPageSetting", SqlDbType.NVarChar, 4000);
                    param[9].Value = st.OtherNewsPageSetting.Trim().Equals("") ? DBNull.Value : (object)st.OtherNewsPageSetting;
                    #endregion 第四步
                }
                DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }

        /// <summary>
        /// 更新采集量
        /// </summary>
        /// <param name="id"></param>
        /// <param name="allcount">外网的总数</param>
        /// <param name="needcount">需要采集的量</param>
        public int myCJcountUpdate(int id,int allcount,int needcount)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();

            string Sql = "update " + Pre + "Collect_Site set allcount=@allcount,needcount=@needcount where ID=" + id;
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@allcount", allcount);
            param[1] = new SqlParameter("@needcount", needcount);           
            int i = DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            cn.Close();
            return i;
        }

        public int myCJNumUpdate(int id, int cjcount)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();

            string Sql = "update " + Pre + "Collect_Site set cjcount=@cjcount where ID=" + id;
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@cjcount", cjcount);            
            int i = DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            cn.Close();
            return i;
        }

        public int myCJTitleUpdate(int ruleid, string title)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();

            string Sql = "update " + Pre + "Collect_Site set topchapter=@topchapter where ID=" + ruleid;
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@topchapter", title);
            int i = DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            cn.Close();
            return i;
        }

        public int mySetCJTime(string ruleid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            string Sql = "update cjqueue set collecttime=getdate() where ruleid=" + ruleid;            
            int i = DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            cn.Close();
            return i;
        }
        public void FolderUpdate(int id, string Name, string Description)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            string Sql = "select count(*) from " + Pre + "Collect_SiteFolder where SiteFolder=@SiteFolder and ChannelID='" + Current.SiteID + "' and ID<>" + id;
            SqlParameter prm = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            prm.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, prm));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("栏目名称重复");
            }
            Sql = "update " + Pre + "Collect_SiteFolder set SiteFolder=@SiteFolder,SiteFolderDetail=@SiteFolderDetail where ChannelID='" + Current.SiteID + "' and ID=" + id;
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@SiteFolder", SqlDbType.NVarChar, 50);
            param[0].Value = Name;
            param[1] = new SqlParameter("@SiteFolderDetail", SqlDbType.NText);
            param[1].Value = Description.Trim().Equals("") ? DBNull.Value : (object)Description;
            DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, param);
            cn.Close();
        }
        private SqlParameter[] GetParameters(CollectSiteInfo st)
        {
            SqlParameter[] pmt = new SqlParameter[21];
            pmt[0] = new SqlParameter("@SiteName", SqlDbType.NVarChar, 50);
            pmt[0].Value = st.SiteName;
            pmt[1] = new SqlParameter("@objURL", SqlDbType.NVarChar, 250);
            pmt[1].Value = st.objURL;
            pmt[2] = new SqlParameter("@Folder", SqlDbType.Int);
            pmt[2].Value = st.Folder < 1 ? DBNull.Value : (object)st.Folder;
            pmt[3] = new SqlParameter("@SaveRemotePic", SqlDbType.Bit);
            pmt[3].Value = st.SaveRemotePic;
            pmt[4] = new SqlParameter("@Audit", SqlDbType.NVarChar, 10);
            pmt[4].Value = st.Audit;
            pmt[5] = new SqlParameter("@IsReverse", SqlDbType.Bit);
            pmt[5].Value = st.IsReverse;
            pmt[6] = new SqlParameter("@IsAutoPicNews", SqlDbType.Bit);
            pmt[6].Value = st.IsAutoPicNews;
            pmt[7] = new SqlParameter("@ClassID", SqlDbType.NVarChar, 50);
            pmt[7].Value = st.ClassID;
            pmt[8] = new SqlParameter("@TextTF", SqlDbType.Bit);
            pmt[8].Value = st.TextTF;
            pmt[9] = new SqlParameter("@IsStyle", SqlDbType.Bit);
            pmt[9].Value = st.IsStyle;
            pmt[10] = new SqlParameter("@IsDIV", SqlDbType.Bit);
            pmt[10].Value = st.IsDIV;
            pmt[11] = new SqlParameter("@IsA", SqlDbType.Bit);
            pmt[11].Value = st.IsA;
            pmt[12] = new SqlParameter("@IsClass", SqlDbType.Bit);
            pmt[12].Value = st.IsClass;
            pmt[13] = new SqlParameter("@IsFont", SqlDbType.Bit);
            pmt[13].Value = st.IsFont;
            pmt[14] = new SqlParameter("@IsSpan", SqlDbType.Bit);
            pmt[14].Value = st.IsSpan;
            pmt[15] = new SqlParameter("@IsObject", SqlDbType.Bit);
            pmt[15].Value = st.IsObject;
            pmt[16] = new SqlParameter("@IsIFrame", SqlDbType.Bit);
            pmt[16].Value = st.IsIFrame;
            pmt[17] = new SqlParameter("@IsScript", SqlDbType.Bit);
            pmt[17].Value = st.IsScript;
            pmt[18] = new SqlParameter("@Encode", SqlDbType.NVarChar, 50);
            pmt[18].Value = st.Encode;
            pmt[19] = new SqlParameter("@IsAutoCollect", SqlDbType.Bit);
            pmt[19].Value = st.IsAutoCollect;
            pmt[20] = new SqlParameter("@cjcount", SqlDbType.Int);
            pmt[20].Value = st.cjcount;
            return pmt;
        }
        public DataTable GetRulePage(int PageIndex, int PageSize, out int RecordCount, out int PageCount)
        {
            return DbHelper.ExecutePage(DBConfig.CollectConString, "ID,RuleName,AddDate", Pre + "Collect_Rule where ChannelID='" + Current.SiteID + "'", "ID", "Order by ID", PageIndex, PageSize, out RecordCount, out PageCount, null);
        }
        public void RuleDelete(int id)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            SqlTransaction trans = cn.BeginTransaction();
            try
            {
                string Sql = "delete from " + Pre + "Collect_RuleApply where RuleID=" + id;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                Sql = "delete from " + Pre + "Collect_Rule where ChannelID='" + Current.SiteID + "' and ID=" + id;
                DbHelper.ExecuteNonQuery(trans, CommandType.Text, Sql, null);
                trans.Commit();
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public int RuleAdd(string Name, string OldStr, string NewStr, int[] AppSites, bool IgnoreCase)
        {
            int id = 0;
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            string Sql = "select count(*) from " + Pre + "Collect_Rule where RuleName=@RuleName and ChannelID='" + Current.SiteID + "'";
            SqlParameter param = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
            param.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("规则名称重复");
            }
            SqlTransaction Trans = cn.BeginTransaction();
            try
            {
                Sql = "insert into " + Pre + "Collect_Rule (RuleName,OldContent,ReContent,AddDate,IgnoreCase,ChannelID) values (@RuleName,@OldContent,@ReContent,@AddDate,@IgnoreCase,'" + Current.SiteID + "')";
                Sql += ";SELECT @@IDENTITY";
                SqlParameter[] parm = new SqlParameter[5];
                parm[0] = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
                parm[0].Value = Name;
                parm[1] = new SqlParameter("@OldContent", SqlDbType.NVarChar, 100);
                parm[1].Value = OldStr;
                parm[2] = new SqlParameter("@ReContent", SqlDbType.NVarChar, 100);
                parm[2].Value = NewStr;
                parm[3] = new SqlParameter("@AddDate", SqlDbType.DateTime);
                parm[3].Value = DateTime.Now;
                parm[4] = new SqlParameter("@IgnoreCase", SqlDbType.Bit);
                parm[4].Value = IgnoreCase;
                id = Convert.ToInt32(DbHelper.ExecuteScalar(Trans, CommandType.Text, Sql, parm));
                if (AppSites != null && AppSites.Length > 0)
                {
                    foreach (int stid in AppSites)
                    {
                        Sql = "delete from " + Pre + "Collect_RuleApply where SiteID=" + stid;
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                        Sql = "insert into " + Pre + "Collect_RuleApply(SiteID,RuleID,RefreshTime) values (" + stid + "," + id + ",'" + DateTime.Now + "')";
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                    }
                }
                Trans.Commit();
            }
            catch
            {
                Trans.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
            return id;
        }
        public void RuleUpdate(int RuleID, string Name, string OldStr, string NewStr, int[] AppSites, bool IgnoreCase)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            string Sql = "select count(*) from " + Pre + "Collect_Rule where RuleName=@RuleName and ChannelID='" + Current.SiteID + "' and ID<>" + RuleID;
            SqlParameter param = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
            param.Value = Name;
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(cn, CommandType.Text, Sql, param));
            if (n > 0)
            {
                cn.Close();
                throw new Exception("规则名称重复");
            }
            SqlTransaction Trans = cn.BeginTransaction();
            try
            {
                Sql = "update " + Pre + "Collect_Rule set RuleName=@RuleName,OldContent=@OldContent,ReContent=@ReContent,IgnoreCase=@IgnoreCase where ChannelID='" + Current.SiteID + "' and ID=" + RuleID;
                SqlParameter[] parm = new SqlParameter[4];
                parm[0] = new SqlParameter("@RuleName", SqlDbType.NVarChar, 50);
                parm[0].Value = Name;
                parm[1] = new SqlParameter("@OldContent", SqlDbType.NVarChar, 100);
                parm[1].Value = OldStr;
                parm[2] = new SqlParameter("@ReContent", SqlDbType.NVarChar, 100);
                parm[2].Value = NewStr;
                parm[3] = new SqlParameter("@IgnoreCase", SqlDbType.Bit);
                parm[3].Value = IgnoreCase;
                DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, parm);
                Sql = "delete from " + Pre + "Collect_RuleApply where RuleID=" + RuleID;
                DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                if (AppSites != null && AppSites.Length > 0)
                {
                    foreach (int stid in AppSites)
                    {
                        Sql = "delete from " + Pre + "Collect_RuleApply where SiteID=" + stid;
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                        Sql = "insert into " + Pre + "Collect_RuleApply(SiteID,RuleID,RefreshTime) values (" + stid + "," + RuleID + ",'" + DateTime.Now + "')";
                        DbHelper.ExecuteNonQuery(Trans, CommandType.Text, Sql, null);
                    }
                }
                Trans.Commit();
            }
            catch
            {
                Trans.Rollback();
                throw;
            }
            finally
            {
                if (cn != null && cn.State == ConnectionState.Open)
                    cn.Close();
            }
        }
        public DataTable GetRule(int id)
        {
            string Sql = "select * from " + Pre + "Collect_Rule where ChannelID='" + Current.SiteID + "' and ID=" + id;
            return DbHelper.ExecuteTable(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }
        public DataTable SiteList()
        {
            string Sql = "select a.id,SiteName,RuleID from " + Pre + "Collect_Site a left outer join " + Pre + "Collect_RuleApply b on a.ID = b.SiteID where a.ChannelID='" + Current.SiteID + "'";
            return DbHelper.ExecuteTable(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }
        public string NewsAdd(CollectNewsInfo newsinfo)
        {
            string Sql = "insert into " + Pre + "Collect_News ([Title],[Links],[Author],[Source],[Content],[AddDate],[ImagesCount],[SiteID],[History],[ReviewTF],[CollectTime],[ChannelID],[ClassID]) values (";
            Sql += "@Title,@Links,@Author,@Source,@Content,@AddDate,0,@SiteID,0,0,'" + DateTime.Now + "','1',@ClassID)select @@IDENTITY";
            //DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, Sql, GetNewsParams(newsinfo));
            object id = DbHelper.ExecuteScalar(DBConfig.CollectConString, CommandType.Text, Sql, GetNewsParams(newsinfo));
            if (id != null) return id.ToString();
            return "-1";
        }
        public bool TitleExist(string title)
        {
            string Sql = "select count(id) from " + Pre + "Collect_News where Title=@Title";
            SqlParameter Param = new SqlParameter("@Title", title);
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(DBConfig.CollectConString, CommandType.Text, Sql, Param));
            if (n > 0)
                return true;
            else
                return false;
        }
        public DataTable GetNewsPage(int PageIndex, int PageSize, out int RecordCount, out int PageCount)
        {
            return DbHelper.ExecutePage(DBConfig.CollectConString, "a.ID,Title,AddDate,SiteName,History,CollectTime", Pre + "Collect_News a left join " + Pre + "Collect_Site b on a.SiteID=b.ID where a.ChannelID='" + Current.SiteID + "'", "a.ID", "Order by History asc,a.ID desc", PageIndex, PageSize, out RecordCount, out PageCount, null);
        }
        public void NewsDelete(string id)
        {
            string Sql = "";
            try
            {
                 Sql = "Delete from " + Pre + "Collect_News where ChannelID='" + Current.SiteID + "'";

            }
            catch (Exception e)
            {
                Sql = "Delete from " + Pre + "Collect_News where ChannelID='1'";
            }
            if (id.Equals("0"))
                Sql += " and History=1";
            else
                Sql += " and ID in (" + id + ")";
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }

        public int myContentDelete(string ruleid)
        {
            string Sql = "";
            try
            {
                Sql = "Delete from " + Pre + "Collect_News where ChannelID='" + Current.SiteID + "'";

            }
            catch (Exception e)
            {
                Sql = "Delete from " + Pre + "Collect_News where ChannelID='1'";
            }
            Sql += " and SiteID =" + ruleid;
            return DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, Sql, null);
        }

        public CollectNewsInfo GetNews(int id)
        {
            CollectNewsInfo info = new CollectNewsInfo();
            string Sql = "select [Title],[Links],[SiteID],[Author],[Source],[AddDate],[Content],[CollectTime],[ClassID] from " + Pre + "Collect_News where ChannelID='" + Current.SiteID + "' and ID=" + id;
            IDataReader rd = DbHelper.ExecuteReader(DBConfig.CollectConString, CommandType.Text, Sql, null);
            if (rd.Read())
            {
                info.Title = rd.GetString(0);
                info.Links = rd.GetString(1);
                info.SiteID = rd.GetInt32(2);
                if (!rd.IsDBNull(3)) info.Author = rd.GetString(3);
                if (!rd.IsDBNull(4)) info.Source = rd.GetString(4);
                if (!rd.IsDBNull(5)) info.AddDate = rd.GetDateTime(5);
                if (!rd.IsDBNull(6)) info.Content = rd.GetString(6);
                info.CollectTime = rd.GetDateTime(7);
                info.ClassID = rd.GetString(8);
            }
            rd.Close();
            return info;
        }
        public void NewsUpdate(int id, CollectNewsInfo info)
        {
            string Sql = "update " + Pre + "Collect_News set [Title]=@Title,[Links]=@Links,[SiteID]=@SiteID,[Author]=@Author";
            Sql += ",[Source]=@Source,[AddDate]=@AddDate,[Content]=@Content,[ClassID]=@ClassID where ChannelID='" + Current.SiteID + "' and ID=" + id;
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, Sql, GetNewsParams(info));
        }
        private SqlParameter[] GetNewsParams(CollectNewsInfo info)
        {
            SqlParameter[] param = new SqlParameter[8];
            param[0] = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
            param[0].Value = info.Title;
            param[1] = new SqlParameter("@Links", SqlDbType.NVarChar, 200);
            param[1].Value = info.Links;
            param[2] = new SqlParameter("@Author", SqlDbType.NVarChar, 100);
            param[2].Value = info.Author==null ? DBNull.Value : (object)info.Author;
            param[3] = new SqlParameter("@Source", SqlDbType.NVarChar, 100);
            param[3].Value = info.Source == null ? DBNull.Value : (object)info.Source;
            param[4] = new SqlParameter("@Content", SqlDbType.NText);
            param[4].Value = info.Content;
            param[5] = new SqlParameter("@AddDate", SqlDbType.DateTime);
            param[5].Value = info.AddDate.Year < 1753 ? DBNull.Value : (object)info.AddDate;
            param[6] = new SqlParameter("@SiteID", SqlDbType.Int);
            param[6].Value = info.SiteID;
            param[7] = new SqlParameter("@ClassID", SqlDbType.NVarChar, 12);
            param[7].Value = info.ClassID;
            return param;
        }
        #region 新闻入库
        ///////////////////////////新闻入库专用///////////////////////////////////////
        private SqlConnection connetion;
        private SqlConnection connetcms;
        private int nStoreSucceed = 0;
        private int nStoreFailed = 0;
        public void StoreNews(bool UnStore, int[] id, out int nSucceed, out int nFailed)
        {
            nSucceed = 0;
            nFailed = 0;
            connetion = new SqlConnection(DBConfig.CollectConString);
            connetcms = new SqlConnection(DBConfig.CmsConString);
            string Sql = "select a.ID,a.Title,a.Links,a.Author,a.Source,a.Content,a.AddDate,a.RecTF,a.TodayNewsTF,a.MarqueeNews";
            Sql += ",a.SBSNews,a.ReviewTF,a.ClassID,b.Audit,b.ID as CID,b.sitename as sitename from " + Pre + "Collect_News a inner join " + Pre + "Collect_Site b";
            //Sql += " on a.ChannelID=b.ID where a.ChannelID='" + Current.SiteID + "'";
            Sql += " on a.SiteID=b.ID where a.ChannelID='1'";
            try
            {
                connetion.Open();
                connetcms.Open();
                if (UnStore)
                {
                    Sql += " and History=0";
                }
                else
                {
                    string strid = "";
                    for (int i = 0; i < id.Length; i++)
                    {
                        if (i > 0)
                            strid += ",";
                        strid += id[i].ToString();
                    }
                    Sql += " and a.id in (" + strid + ")";
                }
                Sql += "order by a.collecttime";
                StoreBookBySQL(Sql);//////////
                nSucceed = nStoreSucceed;
                nFailed = nStoreFailed;
            }
            finally
            {
                StoreEnd();
            }
        }


       

        private void StoreStep(string Sql)
        {           
            DataTable dt = DbHelper.ExecuteTable(connetion, CommandType.Text, Sql, null);
            CollectNewsInfo Info = new CollectNewsInfo();
            foreach (DataRow r in dt.Rows)
            {

                try
                {
                    int id = Convert.ToInt32(r["id"]);
                    string pname = r["Title"].ToString();
                    string bookid = r["ClassID"].ToString();
                    string mycontent = r["Content"].ToString();
                    string cid = r["cid"].ToString();
                    
                    #region 注释
                    /*
                    string sAuthor = "";
                    if (r["Author"] != DBNull.Value) sAuthor = r["Author"].ToString();
                    string sSource = "";
                    if (r["Source"] != DBNull.Value) sSource = r["Source"].ToString();
                    DateTime dtAddDate = DateTime.Now;
                    if (r["AddDate"] != DBNull.Value) dtAddDate = (DateTime)r["AddDate"];
                    IsAudit = (int)r["Audit"];

                    string CheckSate = "3|1|1|1";
                    int IsLock = 1;
                    switch (IsAudit)
                    {
                        case 0:
                            CheckSate = "0|0|0|0";
                            IsLock = 0;
                            break;
                        case 1:
                            CheckSate = "1|1|0|0";
                            break;
                        case 2:
                            CheckSate = "2|1|1|0";
                            break;
                    }
                    #region 取新闻的默认值选项
                    #region 用于保存新闻的变量
                    string NewsPathRule = string.Empty;
                    string NewsFileRule = string.Empty;
                    byte isDelPoint = 0;
                    int Gpoint = 0;
                    int iPoint = 0;
                    string GroupNumber = string.Empty;
                    string FileExName = ".html";
                    string DataLib = Pre + "news";
                    string Temp = string.Empty;
                    string ClassEname = string.Empty;
                    #endregion 用于保存新闻的变量
                    Sql = "select NewsSavePath,NewsFileRule,isDelPoint,Gpoint,iPoint,GroupNumber,FileName,DataLib,ReadNewsTemplet,ClassEName";
                    Sql += " from " + Pre + "news_Class where ClassID='" + sClass + "'";
                    IDataReader rd = DbHelper.ExecuteReader(connetcms, CommandType.Text, Sql, null);
                    if (rd.Read())
                    {
                        #region 赋值
                        ClassEname = rd["ClassEName"].ToString();
                        if (rd["NewsSavePath"] != DBNull.Value)
                            NewsPathRule = rd["NewsSavePath"].ToString();
                        if (rd["NewsFileRule"] != DBNull.Value)
                            NewsFileRule = rd["NewsFileRule"].ToString();
                        if (rd["isDelPoint"] != DBNull.Value)
                            isDelPoint = Convert.ToByte(rd["isDelPoint"]);
                        if (rd["Gpoint"] != DBNull.Value)
                            Gpoint = Convert.ToInt32(rd["Gpoint"]);
                        if (rd["iPoint"] != DBNull.Value)
                            iPoint = Convert.ToInt32(rd["iPoint"]);
                        if (rd["GroupNumber"] != DBNull.Value)
                            GroupNumber = rd["GroupNumber"].ToString();
                        if (rd["FileName"] != DBNull.Value)
                            FileExName = rd["FileName"].ToString();
                        if (rd["DataLib"] != DBNull.Value)
                            DataLib = rd["DataLib"].ToString();
                        if (rd["ReadNewsTemplet"] != DBNull.Value)
                            Temp = rd["ReadNewsTemplet"].ToString();
                        #endregion 赋值
                    }
                    rd.Close();

                    #region 保存的文件名等的计算
                    string SavePath = ExChangeRule(NewsPathRule, sClass, ClassEname, AID);
                    string FileName = "";
                    ContentManage ct = new ContentManage();
                    DataTable ta = ct.sel_newsInfo(1);
                    if (ta != null && ta.Rows.Count > 0)
                    {
                        FileName = ta.Rows[0]["SaveNewsFilePath"].ToString();
                    }
                    if (FileName == "{@TitleName}")
                    {
                        FileName = NetCMS.Common.Public.ConvertE(sTitle);
                    }
                    else
                    {
                        FileName = ExChangeRule(FileName, sClass, ClassEname, AID);
                    }
                    string NewsID = NetCMS.Common.Rand.Number(12);
                    if (FileName == string.Empty)
                        FileName = NetCMS.Common.Rand.Number(12);
                    //while (Convert.ToInt32(DbHelper.ExecuteScalar(connetcms, CommandType.Text, "select count(ID) from " + Pre + "news where NewsID='" + NewsID + "' or FileName='" + FileName + "'", null)) > 0)
                    //{
                    //    NewsID = NetCMS.Common.Rand.Number(12, true);
                    //    //FileName = FileName + "_" + NetCMS.Common.Rand.Number(3, true);
                    //}
                    #endregion
                    #endregion 取新闻的默认值选项
                    
                    Sql = "insert into " + Pre + "news (";
                    Sql += "[NewsID],[NewsType],[NewsTitle],[TitleITF],[URLaddress],[ClassID],[NewsPicTopline],[Author],[Souce],[Templet],[Content],";
                    Sql += "[CreatTime],[isLock],[SiteID],[Editor],[CheckStat],[NewsProperty],[Click],[FileName],[FileEXName],[isDelPoint],[Gpoint],";
                    Sql += "[iPoint],[GroupNumber],[ContentPicTF],[CommTF],[DiscussTF],[TopNum],[VoteTF],[isRecyle],[DataLib],[isVoteTF],[SavePath],";
                    Sql += "[isHtml],[isConstr],[Tags]";
                    Sql += ") values (";
                    Sql += "@NewsID,@NewsType,@NewsTitle,0,@URLaddress,@ClassID,0,@Author,@Souce,@Templet,@Content,";
                    Sql += "@CreatTime,@IsLock,@SiteID,@Editor,@CheckStat,@NewsProperty,0,@FileName,@FileEXName,@isDelPoint,@Gpoint,";
                    Sql += "@iPoint,@GroupNumber,0,1,0,0,0,0,@DataLib,0,@SavePath,";
                    Sql += "0,0,@Tags)";
                    */
                    #endregion

                    Sql = "insert into chapter (";
                    Sql += "[pname],[bookid],[status],[addtime],[edittime],orderby)";                    
                    Sql += " select ";
                    Sql += "@pname,@bookid,0,getdate(),getdate(),max(pid)+1 from chapter ;select @@IDENTITY as newid;";
                    //'" + FileName + "','.html',0,0,0,0,1,1,0,1,0,'"+ Pre +"'News',0,0,0)";
                   
                    SqlParameter[] parms = {              
                       new SqlParameter("@pname",pname),
                       new SqlParameter("@bookid",bookid)                       
                    };                        
                    int pid = int.Parse(DbHelper.ExecuteScalar(connetcms, CommandType.Text, Sql, parms).ToString());//返回的pid,作为TContent内容表的pid
                    string strInsertTContent = "insert into TContent(pid,content) values(@pid,@mycontent)";
                    SqlParameter[] parms1 = {              
                       new SqlParameter("@pid",pid),
                       new SqlParameter("@mycontent",mycontent.Replace("'", "''"))                       
                    };  
					DbHelper.ExecuteNonQuery(connetion, CommandType.Text, strInsertTContent, parms1);
                    //ExecuteScalar

                    //if (nStoreSucceed + 1 == dt.Rows.Count)//最后一条，修改入库总数，修改最新更新和最新章节
                    
                    Sql = "update " + Pre + "Collect_Site set cjcount=cjcount+@cjcount,needcount=needcount-@needcount where classid = " + bookid;
                    SqlParameter[] parms2 = {              
                       new SqlParameter("@cjcount",1),//增加入库数
                       new SqlParameter("@needcount",1)//减去需要采的数                                           
                    };
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, parms2);

                    Sql = "update book set edittime=getdate(),topchapter=@pid where bid=" + bookid;
                    SqlParameter[] parms3 = {              
                       new SqlParameter("@pid",pid)                                           
                    };
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, parms3);
                    

                    Sql = "update " + Pre + "Collect_News set History=1 where ID=" + id;
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                    nStoreSucceed++;                    
                }
                catch(Exception err)
                {
                    //错误日志，入库的时候
                    NetCMS.Common.Public.saveLogFiles(0,"collect","入库的时候失败",err.Message);
                    nStoreFailed++;
                }
            }
            dt.Clear();
            dt.Dispose();
        }
        private void StoreEnd()
        {
            if (connetion != null && connetion.State == ConnectionState.Open)
                connetion.Close();
            if (connetcms != null && connetcms.State == ConnectionState.Open)
                connetcms.Close();
        }

        public void StoreOne(string newid)
        {
            string Sql = "select a.ID,a.Title,a.Links,a.Author,a.Source,a.Content,a.AddDate,a.RecTF,a.TodayNewsTF,a.MarqueeNews";
            Sql += ",a.SBSNews,a.ReviewTF,a.ClassID,b.Audit,b.ID as CID from " + Pre + "Collect_News a inner join " + Pre + "Collect_Site b";
            //Sql += " on a.ChannelID=b.ID where a.ChannelID='" + Current.SiteID + "'";
            Sql += " on a.SiteID=b.ID where a.ChannelID='1' and a.id="+newid;

            SqlConnection connetion = new SqlConnection(DBConfig.CollectConString);            
            SqlConnection connetcms = new SqlConnection(DBConfig.CmsConString);
            DataTable dt = DbHelper.ExecuteTable(connetion, CommandType.Text, Sql, null);
            CollectNewsInfo Info = new CollectNewsInfo();
            foreach (DataRow r in dt.Rows)
            {
                try
                {
                    int id = Convert.ToInt32(r["id"]);
                    string pname = r["Title"].ToString();
                    string bookid = r["ClassID"].ToString();
                    string mycontent = r["Content"].ToString();
                    string cid = r["cid"].ToString();
       
                    Sql = "insert into chapter (";
                    Sql += "[pname],[bookid],[status],[addtime],[edittime],orderby)";
                    Sql += " select ";
                    Sql += "@pname,@bookid,0,getdate(),getdate(),max(pid)+1 from chapter ;select @@IDENTITY as newid;";
                    //'" + FileName + "','.html',0,0,0,0,1,1,0,1,0,'"+ Pre +"'News',0,0,0)";

                    SqlParameter[] parms = {              
                       new SqlParameter("@pname",pname),
                       new SqlParameter("@bookid",bookid)                       
                    };
                    int pid = int.Parse(DbHelper.ExecuteScalar(connetcms, CommandType.Text, Sql, parms).ToString());//返回的pid,作为TContent内容表的pid
                    string strInsertTContent = "insert into TContent(pid,content) values(@pid,@mycontent)";
                    SqlParameter[] parms1 = {              
                       new SqlParameter("@pid",pid),
                       new SqlParameter("@mycontent",mycontent.Replace("'", "''"))                       
                    };
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, strInsertTContent, parms1);
                    //ExecuteScalar

                    //if (nStoreSucceed + 1 == dt.Rows.Count)//最后一条，修改入库总数，修改最新更新和最新章节

                    Sql = "update " + Pre + "Collect_Site set cjcount=cjcount+@cjcount,needcount=needcount-@needcount where classid = " + bookid;
                    SqlParameter[] parms2 = {              
                       new SqlParameter("@cjcount",1),//增加入库数
                       new SqlParameter("@needcount",1)//减去需要采的数                                           
                    };
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, parms2);

                    Sql = "update book set edittime=getdate(),topchapter=@pid where bid=" + bookid;
                    SqlParameter[] parms3 = {              
                       new SqlParameter("@pid",pid)                                           
                    };
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, parms3);

                    Sql = "update " + Pre + "Collect_News set History=1 where ID=" + id;
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);                    
                }
                catch (Exception err)
                {
                    //错误日志，入库的时候
                    NetCMS.Common.Public.saveLogFiles(0, "collect", "入库的时候失败", err.Message);                    
                }
            }
            dt.Clear();
            dt.Dispose();
            if (connetion != null && connetion.State == ConnectionState.Open)
            {
                connetion.Close();
            }
            if (connetcms != null && connetcms.State == ConnectionState.Open)
            {
                connetcms.Close();
            }
        }

        public void StoreOneBook(string newid,string title,string catalogid,string descript,string author,string link)
        {

            SqlConnection connetcms = new SqlConnection(DBConfig.CmsConString);            
            try
            {
                string Sql = "";
                Sql = "insert into book (";
                Sql += "[bname],[catalogid],[catalogname],descript,author,curl,publishtime,status,[addtime],[edittime])";
                Sql += " select @bname,@catalogid,cname,@descript,@author,@curl,getdate(),-1,getdate(),getdate() from catalog where cid=@catalogid";
                //'" + FileName + "','.html',0,0,0,0,1,1,0,1,0,'"+ Pre +"'News',0,0,0)";

                SqlParameter[] parms = {              
                   new SqlParameter("@bname",title),
                   new SqlParameter("@catalogid",catalogid),
                   new SqlParameter("@descript",descript),  
                   new SqlParameter("@author",author),
                   new SqlParameter("@curl",link)
                };
                DbHelper.ExecuteNonQuery(connetcms, CommandType.Text, Sql, parms);
                Sql = "update " + Pre + "Collect_News set History=1 where ID=" + newid;
                DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                nStoreSucceed++;     
            }
            catch (Exception err)
            {
                nStoreFailed++;
                //错误日志，入库的时候
                NetCMS.Common.Public.saveLogFiles(0, "collect", "书籍入库的时候失败", err.Message);
            }
            
          
            if (connetcms != null && connetcms.State == ConnectionState.Open)
            {
                connetcms.Close();
            }
        }

        /// <summary>
        /// 手动挑选几个入库
        /// </summary>
        /// <param name="Sql"></param>
        public void StoreBookBySQL(string Sql)
        {            

            SqlConnection connetion = new SqlConnection(DBConfig.CollectConString);
            SqlConnection connetcms = new SqlConnection(DBConfig.CmsConString);
            DataTable dt = DbHelper.ExecuteTable(connetion, CommandType.Text, Sql, null);
            CollectNewsInfo Info = new CollectNewsInfo();
            foreach (DataRow r in dt.Rows)
            {
                try
                {
                    xfCreateTopic(r);

                    //xfCreatePost(r);

                    Sql = "update " + Pre + "Collect_News set History=1 where ID=" + r["id"].ToString();
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                    nStoreSucceed++;

                }
                catch (Exception err)
                {
                    nStoreFailed++;
                    //错误日志，入库的时候
                    NetCMS.Common.Public.saveLogFiles(0, "collect", "入库的时候失败", err.Message);
                }
            }
            dt.Clear();
            dt.Dispose();
            if (connetion != null && connetion.State == ConnectionState.Open)
            {
                connetion.Close();
            }
            if (connetcms != null && connetcms.State == ConnectionState.Open)
            {
                connetcms.Close();
            }
        }

        public void StoreOne22(string newid)
        {
            string Sql = "select a.ID,a.Title,a.Links,a.Author,a.Source,a.Content,a.AddDate,a.RecTF,a.TodayNewsTF,a.MarqueeNews";
            Sql += ",a.SBSNews,a.ReviewTF,a.ClassID,b.Audit,b.ID as CID from " + Pre + "Collect_News a inner join " + Pre + "Collect_Site b";
            //Sql += " on a.ChannelID=b.ID where a.ChannelID='" + Current.SiteID + "'";
            Sql += " on a.SiteID=b.ID where a.ChannelID='1' and a.id=" + newid;

            SqlConnection connetion = new SqlConnection(DBConfig.CollectConString);
            SqlConnection connetcms = new SqlConnection(DBConfig.CmsConString);
            DataTable dt = DbHelper.ExecuteTable(connetion, CommandType.Text, Sql, null);
            CollectNewsInfo Info = new CollectNewsInfo();
            foreach (DataRow r in dt.Rows)
            {
                try
                {

                    Sql = "insert into book (";
                    Sql += "[bname],[catalogid],[catalogname],descript,author,curl,publishtime,status,[addtime],[edittime])";
                    Sql += " select @bname,@catalogid,cname,@descript,@author,@curl,getdate(),-1,getdate(),getdate() from catalog where cid=@catalogid";
                    //'" + FileName + "','.html',0,0,0,0,1,1,0,1,0,'"+ Pre +"'News',0,0,0)";

                    SqlParameter[] parms = {              
                       new SqlParameter("@bname",r["Title"].ToString()),
                       new SqlParameter("@catalogid",r["ClassID"].ToString()),
                       new SqlParameter("@descript",r["Content"].ToString()),  
                       new SqlParameter("@author",r["author"].ToString()),
                       new SqlParameter("@curl",r["links"].ToString())
                    };
                    DbHelper.ExecuteNonQuery(connetcms, CommandType.Text, Sql, parms);
                    Sql = "update " + Pre + "Collect_News set History=1 where ID=" + newid;
                    DbHelper.ExecuteNonQuery(connetion, CommandType.Text, Sql, null);
                    nStoreSucceed++; 
                }
                catch (Exception err)
                {
                    nStoreFailed++;
                    //错误日志，入库的时候
                    NetCMS.Common.Public.saveLogFiles(0, "collect", "入库的时候失败", err.Message);
                }
            }
            dt.Clear();
            dt.Dispose();
            if (connetion != null && connetion.State == ConnectionState.Open)
            {
                connetion.Close();
            }
            if (connetcms != null && connetcms.State == ConnectionState.Open)
            {
                connetcms.Close();
            }
        }

        private string ExChangeRule(string RuleStr, string classid, string classename, int autoid)
        {
            string RetVal = string.Empty;
            if (RuleStr != null && RuleStr != string.Empty)
            {
                RetVal = RuleStr;
                DateTime Now = DateTime.Now;
                RetVal = Regex.Replace(RetVal, @"\{\@year02\}", Now.Year.ToString().Substring(2, 2), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@year04\}", Now.Year.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@month\}", Now.Month.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@day\}", Now.Day.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@hour\}", Now.Hour.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@minute\}", Now.Minute.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@second\}", Now.Second.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@ClassId\}", classid, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                RetVal = Regex.Replace(RetVal, @"\{\@EName\}", classename, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                Regex reg = new Regex(@"\{\@Ram(?<m>\d+)_(?<n>\d+)\}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                Match match = reg.Match(RetVal);
                while (match.Success)
                {
                    int m = Convert.ToInt32(match.Groups["m"].Value);
                    int n = Convert.ToInt32(match.Groups["n"].Value);
                    string s = match.Value;
                    string rnd = string.Empty;
                    switch (n)
                    {
                        case 0:
                            rnd = NetCMS.Common.Rand.Number(m);
                            break;
                        case 1:
                            rnd = NetCMS.Common.Rand.Str_char(m);
                            break;
                        case 2:
                            rnd = NetCMS.Common.Rand.Str(m);
                            break;
                    }
                    RetVal = RetVal.Replace(s, rnd);
                    match = reg.Match(RetVal);
                }
                RetVal = Regex.Replace(RetVal, @"\{\@自动编号ID\}", autoid.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }
            return RetVal;
        }
        #endregion 新闻入库

        /// <summary>
        /// 修改并同时删除cjqueue中的记录
        /// </summary>
        /// <param name="ruleid"></param>
        /// <returns></returns>
        public int myCJAutoUpdate(int ruleid)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();

            string Sql = "update " + Pre + "Collect_Site set cjstate=(case when cjstate=0 then 1 else (case when cjstate=1 then 2 else 0 end) end) where ID=" + ruleid;            
            int i = DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);

            DelAutoCollectRules();
            GetAutoCollectRules();

            cn.Close();
            return i;
        }

        /// <summary>
        /// 设置采集状态
        /// </summary>
        /// <param name="ruleid"></param>
        /// <param name="cjstate"></param>
        /// <returns></returns>
        public int myCJStateUpdate(int ruleid,int cjstate)
        {
            SqlConnection cn = new SqlConnection(DBConfig.CollectConString);
            cn.Open();
            string Sql = "update " + Pre + "Collect_Site set cjstate=2 where ID=" + ruleid;
            int i = DbHelper.ExecuteNonQuery(cn, CommandType.Text, Sql, null);
            cn.Close();
            return i;
        }

        public int DelAutoCollectRules()
        {
            string sql = "delete from cjqueue where ruleid in(";
            sql += "select ID from NT_Collect_Site where ChannelID='1' and cjstate=0)";
            return DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sql, null);

        }

        /// <summary>
        /// 创建主题
        /// </summary>
        private void xfCreateTopic(DataRow r)
        {
            string Sql = "";
            Discuz.Entity.TopicInfo topicInfo = new Discuz.Entity.TopicInfo();
            //需要获取 fid=classid,title,content,
            topicInfo.Fid = int.Parse(r["classid"].ToString());
            topicInfo.Iconid = 0;
            topicInfo.Title = r["Title"].ToString();
            topicInfo.Typeid = 0;
            topicInfo.Price = 0;
            topicInfo.Poster = "一抹残阳";
            topicInfo.Posterid = 2;
            topicInfo.Postdatetime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
            topicInfo.Lastpost = topicInfo.Postdatetime;
            topicInfo.Lastpostid = 2;
            topicInfo.Lastposter = "一抹残阳";
            topicInfo.Views = 0;
            topicInfo.Replies = 0;
            topicInfo.Displayorder = 0;
            topicInfo.Highlight = "";
            topicInfo.Digest = 0;
            topicInfo.Rate = 0;
            topicInfo.Hide = 0;
            topicInfo.Attachment = 0;
            topicInfo.Moderated = 0;
            topicInfo.Closed = 0;
            topicInfo.Magic = 0;
            topicInfo.Special = 0;
            topicInfo.Attention = 0;           
            //'" + FileName + "','.html',0,0,0,0,1,1,0,1,0,'"+ Pre +"'News',0,0,0)";
            
            SqlParameter[] parms = {              
               new SqlParameter("@fid",topicInfo.Fid),
               new SqlParameter("@iconid",topicInfo.Iconid),
               new SqlParameter("@title",topicInfo.Title),  
               new SqlParameter("@typeid",topicInfo.Typeid),
               new SqlParameter("@readperm",topicInfo.Readperm),
               new SqlParameter("@price", topicInfo.Price),
               new SqlParameter("@poster",topicInfo.Poster),
               new SqlParameter("@posterid",topicInfo.Posterid),
               new SqlParameter("@postdatetime",DateTime.Parse(topicInfo.Postdatetime)),
               new SqlParameter("@lastpost",topicInfo.Lastpost),
               //new SqlParameter("@lastpostid",topicInfo.Lastpostid),
               new SqlParameter("@lastposter",topicInfo.Lastposter),
               new SqlParameter("@views",topicInfo.Views),
               new SqlParameter("@replies",topicInfo.Replies),
               new SqlParameter("@displayorder",topicInfo.Displayorder),
               new SqlParameter("@highlight",topicInfo.Highlight),
               new SqlParameter("@digest",topicInfo.Digest),
               new SqlParameter("@rate",topicInfo.Rate),
               new SqlParameter("@hide",topicInfo.Hide),
               new SqlParameter("@attachment",topicInfo.Attachment),
               new SqlParameter("@moderated",topicInfo.Moderated),
               new SqlParameter("@closed",topicInfo.Closed),
               new SqlParameter("@magic",topicInfo.Magic),
               new SqlParameter("@special",topicInfo.Special),
               new SqlParameter("@attention",topicInfo.Attention)
            };

            Sql = "insert into dnt_topics ([fid],[iconid],[title],typeid,readperm,price,poster,posterid,[postdatetime],[lastpost],lastpostid,lastposter,"+
                "views,replies,displayorder,digest,rate,hide,attachment,moderated,closed,magic,special,attention)";
            Sql += " select top 1 @fid,@iconid,@title,@typeid,@readperm,@price,@poster,@posterid,@postdatetime,@lastpost,0,@lastposter," +
                "@views,@replies,@displayorder,@digest,@rate,@hide,@attachment,@moderated,@closed,@magic,@special,@attention from dnt_topics;select @@IDENTITY as newid; ";
                      

            int tid = int.Parse(DbHelper.ExecuteScalar(DBConfig.CollectConString, CommandType.Text, Sql, parms).ToString());
            topicInfo.Tid = tid;

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("UPDATE [dnt_statistics] SET [totaltopic]=[totaltopic] + 1");
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), null);

            sb1.Remove(0, sb1.Length);
            sb1.Append("UPDATE [dnt_forums] SET [topics] = [topics] + 1,[curtopics] = [curtopics] + 1 WHERE [fid] = " + topicInfo.Fid);
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), null);

            sb1.Remove(0, sb1.Length);
            sb1.Append("INSERT INTO [dnt_mytopics]([tid],[uid],[dateline]) VALUES(@topicid,  @posterid,  @postdatetime)");
            SqlParameter[] p1 = {              
               new SqlParameter("@topicid",topicInfo.Tid),
               new SqlParameter("@posterid",topicInfo.Posterid),
               new SqlParameter("@postdatetime",DateTime.Parse(topicInfo.Postdatetime))
            };
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), p1);

           
            xfCreatePost(topicInfo,r["content"].ToString());


            
            
        }

        /// <summary>
        /// 创建帖子
        /// </summary>
        private void xfCreatePost(Discuz.Entity.TopicInfo topicinfo,string content)
        {
            Discuz.Entity.PostInfo postInfo = new Discuz.Entity.PostInfo();
            
            postInfo.Fid = topicinfo.Fid;
            postInfo.Tid = topicinfo.Tid;
            postInfo.Parentid = 0;
            postInfo.Poster = topicinfo.Poster;
            postInfo.Posterid = topicinfo.Posterid;

            postInfo.Title = topicinfo.Title;
            postInfo.Topictitle = topicinfo.Title;
            postInfo.Postdatetime = topicinfo.Postdatetime;
            postInfo.Message = content;
            postInfo.Ip = "127.0.0.1";
            postInfo.Lastedit = topicinfo.Postdatetime;

            postInfo.Usesig = 1;
            postInfo.Invisible = 0;            
            postInfo.Htmlon = 1;
            postInfo.Smileyoff = 1;
            postInfo.Bbcodeoff = 1;
            postInfo.Parseurloff = 1;

            postInfo.Attachment = 0;
            postInfo.Rate = 0;
            postInfo.Ratetimes = 0;


            StringBuilder sb1 = new StringBuilder();
            sb1.Append("DELETE FROM [dnt_postid] WHERE DATEDIFF(n, postdatetime, GETDATE()) >5");
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), null);

            sb1.Remove(0, sb1.Length);
            sb1.Append("INSERT INTO [dnt_postid] ([postdatetime]) VALUES(GETDATE());select @@IDENTITY as newid;");
            int postid = int.Parse(DbHelper.ExecuteScalar(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), null).ToString());
            postInfo.Pid = postid;

            SqlParameter[] parms = {     
               new SqlParameter("@pid",postInfo.Pid),
               new SqlParameter("@fid",postInfo.Fid),
			   new SqlParameter("@tid",postInfo.Tid),
			   new SqlParameter("@parentid",postInfo.Parentid),
			   new SqlParameter("@layer",postInfo.Layer),
			   new SqlParameter("@poster",postInfo.Poster),
			   new SqlParameter("@posterid",postInfo.Posterid),

			   new SqlParameter("@title",postInfo.Title),
			   //new SqlParameter("@topictitle",postInfo.Topictitle),
			   new SqlParameter("@postdatetime", DateTime.Parse(postInfo.Postdatetime)),
			   new SqlParameter("@message",postInfo.Message),
			   new SqlParameter("@ip",postInfo.Ip),
			   new SqlParameter("@lastedit",postInfo.Lastedit),
			   new SqlParameter("@invisible",postInfo.Invisible),

			   new SqlParameter("@usesig",postInfo.Usesig),
			   new SqlParameter("@htmlon",postInfo.Htmlon),
			   new SqlParameter("@smileyoff",postInfo.Smileyoff),
			   new SqlParameter("@bbcodeoff",postInfo.Bbcodeoff),
			   new SqlParameter("@parseurloff",postInfo.Parseurloff),
			   new SqlParameter("@attachment",postInfo.Attachment),
			   new SqlParameter("@rate",postInfo.Rate),
			   new SqlParameter("@ratetimes",postInfo.Ratetimes)
            };
            string Sql = "";
            Sql = "insert into dnt_posts1 (pid,[fid],tid,parentid,layer,poster,posterid,title,postdatetime,message,ip,lastedit,invisible,usesig,htmlon,smileyoff,bbcodeoff,parseurloff" +
                ",attachment,rate,ratetimes)";
            Sql += " select top 1 @pid,@fid,@tid,@parentid,@layer,@poster,@posterid,@title,@postdatetime,@message,@ip,@lastedit,@invisible,@usesig,@htmlon,@smileyoff,@bbcodeoff,@parseurloff" +
            ",@attachment,@rate,@ratetimes from dnt_posts1";

            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, Sql, parms);
            
            
            string fidlist = AddParentForumCount(postInfo.Fid);
                       

            sb1.Remove(0, sb1.Length);
            sb1.Append("UPDATE [dnt_statistics] SET [totalpost]=[totalpost] + 1");
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), null);

            sb1.Remove(0, sb1.Length);
            sb1.Append("UPDATE [dnt_forums] SET  [posts]=[posts] + 1,[todayposts]=CASE WHEN DATEDIFF(day, [lastpost], GETDATE())=0 THEN [todayposts] + 1 ELSE 1  END,");
            sb1.Append("[lasttid]=@tid,[lasttitle]=@topictitle,[lastpost]=@postdatetime,[lastposter]=@poster,[lastposterid]=@posterid ");
            sb1.Append(" WHERE fid IN (SELECT [item] FROM [dnt_split](@fidlist, ','))");
            SqlParameter[] param1 = {     
               new SqlParameter("@tid",postInfo.Tid),new SqlParameter("@topictitle",postInfo.Title),new SqlParameter("@postdatetime",postInfo.Postdatetime),new SqlParameter("@poster",postInfo.Poster),
               new SqlParameter("@posterid",postInfo.Posterid),new SqlParameter("@fidlist",fidlist)
            };
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), param1);

            sb1.Remove(0, sb1.Length);
            sb1.Append("UPDATE [dnt_users] SET [lastpost] = @postdatetime, [lastpostid] = @postid,  [lastposttitle] = @title,  [posts] = [posts] + 1, ");
            sb1.Append("[lastactivity] = GETDATE() WHERE [uid] = @posterid ");
            SqlParameter[] param2 = {     
               new SqlParameter("@postdatetime",postInfo.Postdatetime),new SqlParameter("@postid",postInfo.Pid),new SqlParameter("@title",postInfo.Title),
               new SqlParameter("@posterid",postInfo.Posterid)
            };
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), param2);
            

            sb1.Remove(0, sb1.Length);
            sb1.Append("UPDATE [dnt_topics] SET [lastpostid]="+postInfo.Pid+" WHERE [tid]="+postInfo.Tid);
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), null);


            sb1.Remove(0, sb1.Length);
            sb1.Append("INSERT [dnt_myposts]([uid], [tid], [pid], [dateline]) VALUES(@posterid, @tid, @postid, @postdatetime)");
            SqlParameter[] param3 = {     
               new SqlParameter("@posterid",postInfo.Posterid),new SqlParameter("@tid",postInfo.Tid),new SqlParameter("@postid",postInfo.Pid),
               new SqlParameter("@postdatetime",postInfo.Postdatetime)
            };
            DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sb1.ToString(), param3);
            
        }

        ///////////////////////////////////////

        public ForumInfo GetForumInfo(int fid, bool clone)
        {
            if (fid < 1)
                return null;

            List<ForumInfo> forumList = GetForumList();
            if (forumList == null)
                return null;

            foreach (ForumInfo foruminfo in forumList)
            {
                if (foruminfo.Fid == fid)
                {
                    foruminfo.Pathlist = foruminfo.Pathlist.Replace("a><a", "a> &raquo; <a");
                    return clone ? foruminfo.Clone() : foruminfo;
                }
            }
            return null;
        }

        public List<ForumInfo> GetForumList()
        {
            List<ForumInfo> forumlist = new List<ForumInfo>();
            DataTable dt = GetForumsTable();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    ForumInfo forum = new ForumInfo();
                    forum.Fid = TypeConverter.StrToInt(dr["fid"].ToString(), 0);
                    forum.Parentid = TypeConverter.StrToInt(dr["parentid"].ToString(), 0);
                    forum.Layer = TypeConverter.StrToInt(dr["layer"].ToString(), 0);
                    forum.Pathlist = dr["pathlist"].ToString();
                    forum.Parentidlist = dr["parentidlist"].ToString();
                    forum.Subforumcount = TypeConverter.StrToInt(dr["subforumcount"].ToString(), 0);
                    forum.Name = dr["name"].ToString();
                    forum.Status = TypeConverter.StrToInt(dr["status"].ToString(), 0);
                    forum.Colcount = TypeConverter.StrToInt(dr["colcount"].ToString(), 0);
                    forum.Displayorder = TypeConverter.StrToInt(dr["displayorder"].ToString(), 0);
                    forum.Templateid = TypeConverter.StrToInt(dr["templateid"].ToString(), 0);
                    forum.Topics = TypeConverter.StrToInt(dr["topics"].ToString(), 0);
                    forum.CurrentTopics = TypeConverter.StrToInt(dr["curtopics"].ToString(), 0);
                    forum.Posts = TypeConverter.StrToInt(dr["posts"].ToString(), 0);
                    //当前版块的最后发帖日期为空，则表示今日发帖数为0 
                    if (string.IsNullOrEmpty(dr["lastpost"].ToString()))
                        dr["todayposts"] = 0;
                    else
                    {
                        //当系统日期与最发发帖日期不同时，则表示今日发帖数为0 
                        if (Convert.ToDateTime(dr["lastpost"]).ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd"))
                            dr["todayposts"] = 0;
                    }
                    forum.Todayposts = TypeConverter.StrToInt(dr["todayposts"].ToString(), 0);
                    forum.Lasttid = TypeConverter.StrToInt(dr["lasttid"].ToString(), 0);
                    forum.Lasttitle = dr["lasttitle"].ToString();
                    forum.Lastpost = dr["lastpost"].ToString();
                    forum.Lastposterid = TypeConverter.StrToInt(dr["lastposterid"].ToString(), 0);
                    forum.Lastposter = dr["lastposter"].ToString();
                    forum.Allowsmilies = TypeConverter.StrToInt(dr["allowsmilies"].ToString(), 0);
                    forum.Allowrss = TypeConverter.StrToInt(dr["allowrss"].ToString(), 0);
                    forum.Allowhtml = TypeConverter.StrToInt(dr["allowhtml"].ToString(), 0);
                    forum.Allowbbcode = TypeConverter.StrToInt(dr["allowbbcode"].ToString(), 0);
                    forum.Allowimgcode = TypeConverter.StrToInt(dr["allowimgcode"].ToString(), 0);
                    forum.Allowblog = TypeConverter.StrToInt(dr["allowblog"].ToString(), 0);
                    forum.Istrade = TypeConverter.StrToInt(dr["istrade"].ToString(), 0);
                    forum.Allowpostspecial = TypeConverter.StrToInt(dr["allowpostspecial"].ToString(), 0);
                    forum.Allowspecialonly = TypeConverter.StrToInt(dr["allowspecialonly"].ToString(), 0);
                    forum.Alloweditrules = TypeConverter.StrToInt(dr["alloweditrules"].ToString(), 0);
                    forum.Allowthumbnail = TypeConverter.StrToInt(dr["allowthumbnail"].ToString(), 0);
                    forum.Allowtag = TypeConverter.StrToInt(dr["allowtag"].ToString(), 0);
                    forum.Recyclebin = TypeConverter.StrToInt(dr["recyclebin"].ToString(), 0);
                    forum.Modnewposts = TypeConverter.StrToInt(dr["modnewposts"].ToString(), 0);
                    forum.Modnewtopics = TypeConverter.StrToInt(dr["modnewtopics"].ToString(), 0);
                    forum.Jammer = TypeConverter.StrToInt(dr["jammer"].ToString(), 0);
                    forum.Disablewatermark = TypeConverter.StrToInt(dr["disablewatermark"].ToString(), 0);
                    forum.Inheritedmod = TypeConverter.StrToInt(dr["inheritedmod"].ToString(), 0);
                    forum.Autoclose = TypeConverter.StrToInt(dr["autoclose"].ToString(), 0);

                    forum.Password = dr["password"].ToString();
                    forum.Icon = dr["icon"].ToString();
                    forum.Postcredits = dr["postcredits"].ToString();
                    forum.Replycredits = dr["replycredits"].ToString();
                    forum.Redirect = dr["redirect"].ToString();
                    forum.Attachextensions = dr["attachextensions"].ToString();
                    forum.Rules = dr["rules"].ToString();
                    forum.Topictypes = dr["topictypes"].ToString();
                    forum.Viewperm = dr["viewperm"].ToString();
                    forum.Postperm = dr["postperm"].ToString();
                    forum.Replyperm = dr["replyperm"].ToString();
                    forum.Getattachperm = dr["getattachperm"].ToString();
                    forum.Postattachperm = dr["postattachperm"].ToString();
                    forum.Moderators = dr["moderators"].ToString();
                    forum.Description = dr["description"].ToString();
                    forum.Applytopictype = TypeConverter.StrToInt(dr["applytopictype"] == DBNull.Value ? "0" : dr["applytopictype"].ToString(), 0);
                    forum.Postbytopictype = TypeConverter.StrToInt(dr["postbytopictype"] == DBNull.Value ? "0" : dr["postbytopictype"].ToString(), 0);
                    forum.Viewbytopictype = TypeConverter.StrToInt(dr["viewbytopictype"] == DBNull.Value ? "0" : dr["viewbytopictype"].ToString(), 0);
                    forum.Topictypeprefix = TypeConverter.StrToInt(dr["topictypeprefix"] == DBNull.Value ? "0" : dr["topictypeprefix"].ToString(), 0);
                    forum.Permuserlist = dr["permuserlist"].ToString();
                    forum.Seokeywords = dr["seokeywords"].ToString();
                    forum.Seodescription = dr["seodescription"].ToString();
                    forum.Rewritename = dr["rewritename"].ToString();
                    forumlist.Add(forum);
                }
            }
            return forumlist;
        }

        DataTable GetForumsTable()
        {
            StringBuilder sql = new StringBuilder();
       
            sql.Append(" SELECT [f].[fid],[f].[parentid],[f].[layer],[f].[pathlist],[f].[parentidlist],[f].[subforumcount],");
            sql.Append("[f].[name],[f].[status],[f].[colcount],[f].[displayorder],[f].[templateid],[f].[topics],[f].[curtopics],");
            sql.Append("[f].[posts],[f].[todayposts],[f].[lasttid],[f].[lasttitle],[f].[lastpost],[f].[lastposterid],");
            sql.Append("[f].[lastposter],[f].[allowsmilies],[f].[allowrss],[f].[allowhtml],[f].[allowbbcode],");
            sql.Append("[f].[allowimgcode],[f].[allowblog],[f].[istrade],[f].[allowpostspecial],[f].[allowspecialonly],");
            sql.Append("[f].[alloweditrules],[f].[allowthumbnail],[f].[allowtag],[f].[recyclebin],[f].[modnewposts],");
            sql.Append("[f].[modnewtopics],[f].[jammer],[f].[disablewatermark],[f].[inheritedmod],[f].[autoclose],");
            sql.Append("[ff].[password],[ff].[icon],[ff].[postcredits],[ff].[replycredits],[ff].[redirect],");
            sql.Append("[ff].[attachextensions],[ff].[rules],[ff].[topictypes],[ff].[viewperm],[ff].[postperm],");
            sql.Append("[ff].[replyperm],[ff].[getattachperm],[ff].[postattachperm],[ff].[moderators],[ff].[description],");
            sql.Append("[ff].[applytopictype],[ff].[postbytopictype],[ff].[viewbytopictype],[ff].[topictypeprefix],");
            sql.Append("[ff].[permuserlist],[ff].[seokeywords],[ff].[seodescription],[ff].[rewritename] ");
            sql.Append("FROM [dnt_forums] AS [f] LEFT JOIN [dnt_forumfields] AS [ff] ");
            sql.Append("ON [f].[fid]=[ff].[fid] ORDER BY [f].[displayorder]");
             

            return DbHelper.ExecuteTable(DBConfig.CollectConString, CommandType.Text, sql.ToString(), null);
        }

        private string AddParentForumCount(int forumid)
        {
            Discuz.Entity.ForumInfo forum = GetForumInfo(forumid, true);
            try
            {
                

                StringBuilder sql = new StringBuilder();
                sql.Append("UPDATE [dnt_forums] SET [topics] = [topics] + @topics WHERE [fid] IN (SELECT [item] FROM [dnt_split](@fpidlist, ','))");
                SqlParameter[] parms = {     
                   new SqlParameter("@topics",1),
                   new SqlParameter("@fpidlist",forum.Parentidlist)
                };
                DbHelper.ExecuteNonQuery(DBConfig.CollectConString, CommandType.Text, sql.ToString(), parms);
                return forum.Parentidlist;
            }
            catch (Exception err)
            {
                NetCMS.Common.Public.saveLogFiles(0, "AddParentForumCount()", "板块" + forumid.ToString() + "=" + forum.Parentidlist, err.Message);
            }
            return "";
        }
        
    }
}
